﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

/// <summary> 
/// A class used by Tasks to report progress or completion updates back to the UI. 
/// 
/// 참고: http://blog.stephencleary.com/2010/06/reporting-progress-from-tasks.html
/// </summary> 
namespace LicenseAutoDetection
{
    public sealed class ProgressReporter
    {
        /// <summary> 
        /// The underlying scheduler for the UI's synchronization context. 
        /// </summary> 
        private readonly TaskScheduler scheduler;

        /// <summary> 
        /// Initializes a new instance of the <see cref="ProgressReporter"/> class.
        /// This should be run on a UI thread. 
        /// </summary> 
        public ProgressReporter()
        {
            this.scheduler = TaskScheduler.FromCurrentSynchronizationContext();
        }

        /// <summary> 
        /// Gets the task scheduler which executes tasks on the UI thread. 
        /// </summary> 
        public TaskScheduler Scheduler
        {
            get { return this.scheduler; }
        }

        /// <summary> 
        /// Reports the progress to the UI thread, and waits for the UI thread to process
        /// the update before returning. This method should be called from the task. 
        /// </summary> 
        /// <param name="action">The action to perform in the context of the UI thread.</param> 
        public void Update(Action action)
        {
            Action wrapper = delegate() {
                try
                {
                    action();
                }
                catch
                {
                    // skip
                }
            };

            Task.Factory.StartNew(wrapper, CancellationToken.None, TaskCreationOptions.None, this.scheduler).Wait();
        }
    }
}

